'''
Author: duliang thinktanker@163.com
Date: 2024-07-14 12:23:14
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-09-27 23:24:06
FilePath: 
Description: 
'''
import requests
import os
from PIL import Image, ImageDraw
import base64
# import cv2
from collections import deque

# import numpy as np
# import io


def ocr(imgpath, user):
    with open(imgpath, 'rb') as f:
        resp = requests.post('http://localhost:28211/ocr',
                             files={"imgbin": f.read()},
                             verify=False)
        result = resp.json()
        # print(result)
        if result:
            base64_img = markpic(imgpath, result[-1], user)
            return result, base64_img
        else:
            return None


def ocrimagebytes(imagebytes, user):
    resp = requests.post('http://localhost:28211/ocr',
                         files={"imgbin": imagebytes},
                         verify=False)
    result = resp.json()
    # print(result)
    if result:
        # base64_img = markpic(imagebytes, result[-1], user)
        return result, None
    else:
        return None


def markpic(picpath, resultlist, user):
    '''
    标记已经识别到的区域，调试用
    '''
    img = Image.open(picpath)
    print(picpath)
    picpath = str(picpath).replace('\\', '/')
    # ./wximage/oPQDE5KA-SXhlayCSSaH6VoB31Pk/1720942887.jpg
    picpath = str(picpath).rsplit('/', 1)[-1]
    print(picpath)
    a = ImageDraw.ImageDraw(img)
    # rectangle 坐标的参数格式为左上角（x1, y1），右下角（x2, y2）。
    # print(resultlist)
    for box_array in resultlist:
        box = [[int(coord) for coord in point] for point in box_array]
        # print(box)
        try:
            a.rectangle(((box[0][0], box[0][1]), (box[2][0], box[2][1])),
                        fill=None,
                        outline='red',
                        width=2)
        except Exception as e:
            print(f'Error drawing rectangle: {e}')
            continue
    if not os.path.exists(f'./markpic/{user}'):
        os.mkdir(f'./markpic/{user}')
    img.save(f'./markpic/{user}/{picpath}', quality=1)
    img.save(f'./markpic/{user}/high_{picpath}', quality=90)
    base64_img = None
    with open(f'./markpic/{user}/{picpath}', 'rb') as f:
        base64_img = base64.b64encode(f.read())
    return base64_img


if __name__ == '__main__':

    result, _ = ocr(
        r'D:\myGitee\control-net\wximage\oPQDE5L3OemyvRexvOAeHYqXgA44\fapiao\2025-08-08 094145.jpg',
        'test')
    print(result[0])
